﻿<%@ WebHandler Language="C#" Class="ReportOutputHandler" %>

/*------------------------------------*/
/* Summary description for  WSgcGobal_StyleSheet */
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.OleDb;
using System.Data;
using System.Data.Common;
using zgc0Admin;
using zgc0LibAdmin;
using System.Text;
using gcLibAdmin;
using System.IO;
using System.Web.SessionState;
public class ReportOutputHandler : IHttpHandler, IReadOnlySessionState
{
    string _Id = "-1";

    String strOrderBy;
    double Number = 0;
    string StrConvert = "";
    string headerStr = "<table class=\"rptprintBodyTable\" width=\"800px\" style=\"background:#FFFFFF\">"
			+ "<tr>"
                        + "<td colspan=\"2\" style='font-size:12px;'> &nbsp;</td>"
                        + "</tr>"
                        + "<tr>"
			+ "<tr>"
                     + "<td width=\"500px\"align=\"center\" ><span style='font-weight:bold;font-size:18px;'> {2} </span>  </br><span style='font-size:12px;'>Điện thoại: <strong>{3}</strong> &nbsp;Địa chỉ: {4}</br></span></td>"
                        + "<td></td>"
                        + "</tr>"
                        + "<tr>"
                        + "<tr>"
                        + "<td align=\"center\" colspan=\"2\" width=\"400px\"><b><font size=\"4.0pt\" style='font-weight:bold;font-size:16px;'>PHIẾU XUẤT HÀNG</font></b> </br>"
                        + "<span style='font-size:14px;'>Số phiếu:{0} - Ngày: {1} </span><br/>"
                        + "</td>"
                        + "</tr>"
                        + "<tr>"
                        + "<td colspan=\"2\" style='font-size:12px;'> Người bán: <strong>{5}</strong> - Nhân viên: <strong>{6}</strong></td>"
                        + "</tr>"
                        + "<tr>"
                        + "<td colspan=\"2\" style='font-size:12px;'></td>"
                        + "</tr>"
                    + "</table>";//width=\"670px\"

    string footerStr = "<table class=\"rptprintBodyTable\" width=\"800\" style=\"background:#FFFFFF\">"
                        + "<tr>"
                        + "<td align=\"center\" colspan=\"2\" width=\"400px\"><b><font size=\"4.0pt\" style='font-weight:bold;font-size:16px;'></font></b> </br>"
                        + "<span style='font-size:14px;'> </span><br/>"
                        + "</td>"
                        + "</tr>"

                        + "<tr>"
                        + "<td align=\"center\" colspan=\"2\" width=\"400px\"><b><font size=\"4.0pt\" >&nbsp; </br>"
                        + "<span style='font-size:14px;'> </span><br/>"
                        + "</td>"
                        + "</tr>"
                    + "</table>";
    //Nhà sàn//Bờ Sông//Bè cá//Phòng lạnh//Nhà cổ
    public void ProcessRequest (HttpContext context) {
        //context.Response.ContentType = ResponseFormat

       

        string typeReport = gcUtility.GetNullString(context.Request.Form["typeReport"]);
        string t1 = gcUtility.GetNullString(context.Request.Form["obj[t1]"]);
        string t2 = gcUtility.GetNullString(context.Request.Form["obj[t2]"]);
        string Name = gcUtility.GetNullString(context.Request.Form["obj[Name]"]);
        _Id = gcUtility.GetNullString(context.Request.Form["obj[Id]"]);
        
        

        if (gcUtility.GetNullString(context.Session["zgc0Login_OK"])== "true")
        {
            //Session["gcCtyId"] = ctyId;
            //Session["gcBranchId"] = branchId;
            //Session["gcDepartmentId"] = departmentId;
            //Session["gcUserInfo"] = MaCanBoId;
            //Session["gcUserName"] = txtUsername.Value;
            //Session["gcUserNameSec"] = zgc0HelperSecurity.Encript(txtUsername.Value);
            //Session["gcAccountId"] = myData.Rows[0]["Id"].ToString();//Lay ID
            //Session["gcMaCanBoId"] = myData.Rows[0]["MaCanBoId"].ToString();// Lay ID
            //Session["zgc0Login_OK"] = "true";
            //Session["gcRightGroup"] = myData.Rows[0]["MaQuyenId"].ToString();// Lay nhóm quyền
            //Session["gczNewGroupRight"] = myData.Rows[0]["MaQuyenId"].ToString();// Lay nhóm quyền

            if (typeReport == "Receipt")
            {

                string COMName = "";
                string COMTel = "";
                string COMAdd = "";
                string COMMobile = "";
                string MSHD = "";
                string Sql = "Select * from gcGobal_COMP_Branch ";
                if (HttpContext.Current.Session["gcBranchId"] != null)
                {
                    Sql = String.Format("Select * from gcGobal_COMP_Branch where id = {0}", HttpContext.Current.Session["gcBranchId"].ToString());
                    DataTable tb = zgc0HelperSecurity.GetDataTableNew(Sql, zgc0GlobalStr.getSqlStr());
                    if (tb.Rows.Count > 0)
                    {
                        COMName = tb.Rows[0]["NAME"].ToString().ToUpper();
			COMName = COMName.Replace("-","</br>");
                        COMTel = tb.Rows[0]["TEL"].ToString();
                        COMMobile = tb.Rows[0]["MOBILE"].ToString();
                        COMAdd = tb.Rows[0]["ADDRESS"].ToString();
                    }
                }

                dhuDictionary Dict = new dhuDictionary();
                dhuConvertNumberToString NumberConvert = new dhuConvertNumberToString();
                
                //divBody.InnerHtml = "";
                //divHeader.InnerHtml = "";
                string name = zgc0Helper.getConfigValue("Logopath1");

                bool bEmpty = false;
                DataTable PhieuThu_Print = zgc0HelperSecurity.GetDataTableNew("SELECT * FROM zgcl_gcGobal_STOCK_gcProduct_Output04 where Id=" + _Id, zgc0GlobalStr.getSqlStr());
                if (PhieuThu_Print.Rows.Count < 1)
                {
                    PhieuThu_Print = zgc0HelperSecurity.GetDataTableNew("SELECT * FROM zgcl_gcGobal_STOCK_gcProduct_Output04 where Id=" + _Id, zgc0GlobalStr.getSqlStr());
                    bEmpty = true;
                }
                //DataTable tbKH = zgc0HelperSecurity.GetDataTableNew("SELECT * FROM gcGobal_CUST_Customer where Id=" + PhieuThu_Print.Rows[0]["KHId"].ToString(), zgc0GlobalStr.getSqlStr());
                string LoaiKhachId = "";
                //LoaiKhachId = tbKH.Rows[0]["LoaiKhachId"].ToString();

                //----------------------------------------------------------

                string NhanVienIdHoTen = "THU NGÂN";
                if (PhieuThu_Print.Rows.Count >0)
                {
                    NhanVienIdHoTen = PhieuThu_Print.Rows[0].IsNull("NhanVienIdHoTen")?  "THU NGÂN": PhieuThu_Print.Rows[0]["NhanVienIdHoTen"].ToString(); 
                }
                string BanAn = "";// PhieuThu_Print.Rows[0]["Keep02"].ToString();
                DataTable tblBanAn = zgc0HelperSecurity.GetDataTableNew("SELECT * FROM gcGobal_QA_Table where Id=" + BanAn, zgc0GlobalStr.getSqlStr());
                if (tblBanAn.Rows.Count >0)
                {
                    BanAn = tblBanAn.Rows[0]["Name"].ToString(); 
                 }
                BanAn = BanAn.ToUpper();
                
                
                string SoCT = PhieuThu_Print.Rows[0]["Ten"].ToString();
                SoCT = SoCT.Replace("PT000", "");
                string tempHead = String.Format(headerStr,
                                SoCT, 
                                (String.Format("{0:dd/MM/yyyy hh:mm}", DateTime.Now)),
                                 COMName, COMTel, COMAdd, BanAn, NhanVienIdHoTen);

                string strWhere = "";
                strWhere = "PhieuThuTienMatId=" + _Id + " AND ((isPrgbUserDeleted IS NULL) OR (isPrgbUserDeleted<1))";
                double ThucThu = 0;
                double VAT = 0;
                double PhuThu = 0;// PhieuThu_Print.Rows[0].IsNull("PhuThu") ? 0 : Convert.ToDouble(PhieuThu_Print.Rows[0]["PhuThu"]);
                double GiamGia = 0;// PhieuThu_Print.Rows[0].IsNull("DiscountCust") ? 0 : Convert.ToDouble(PhieuThu_Print.Rows[0]["DiscountCust"]);
                string strTien = "";
                //double GiamGia = 0;

                System.Text.StringBuilder sb = new System.Text.StringBuilder(tempHead+ 
                    BuildAReport(_Id, strWhere, strOrderBy, ref Number, ref ThucThu,
                                            ref PhuThu, ref GiamGia, ref VAT, bEmpty) + footerStr );
                context.Response.ContentType = "text/plain";
                context.Response.Write(sb.ToString());
            }
            
            
        }
        else
            context.Response.Write("Unknown.");
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

    public string BuildAReport(string Id, string strWhere, string strOrderBy, ref double StrConvert, ref double OldThucThu,
        ref double OldPhuThu, ref double OldGiamGia, ref double VAT, bool bEmpty)
    {
        dhuConvertNumberToString NumberConvert = new dhuConvertNumberToString();

        strOrderBy = " order by DonGia ";
        string table = "";
        gcRptTable tblReport = new gcRptTable();//Hàng hóa
        tblReport.strTblSql = @"SELECT VatTuIdName,DonGia,DonViTinhIdName, Sum(SoLuong) AS SoLuong,SUM(ThanhTien) AS ThanhTien FROM zgcl_gcGobal_STOCK_gcProduct_Output_Detail02 WHERE PhieuXuatKhoId=" + _Id + " GROUP BY VatTuIdName,DonViTinhIdName, DonGia";
        
        //-----------------------------------------------------------
        //Cài đặt báo cáo tự động
        //mMaxLevel số mức tối đa của cây
        
        tblReport.strMainTable = "zgcl_gcGobal_INCOM_Receipt_DetailAll";
        tblReport.bShowIndexRow = false;
        tblReport.mColMergForSubSumRow = 5;



        tblReport.mTypeBuild = "isSimple";
        tblReport.bShowSTT = true;
        tblReport.strOrderBy = strOrderBy;
        tblReport.server = zgc0GlobalStr.getSqlStr();
        tblReport.strWhere = strWhere;
        //add danh sách các vị trí cần group by
        //nếu không cần group by thì bỏ qua các cài đặt dưới đây
        tblReport.mArrPos = new int[1];
        //tblReport.mArrPos[0] = 1;//1 ở đây là cột 1, cột 0 đã chứa số thứ tự không thì chúng ta sét cột 0 vào
        //tblReport.mStrShowContent.Add("");//Tương ứng với 3 phần tử trên
        //tblReport.mArrPos[1] = 2;//1 ở đây là cột 1, cột 0 đã chứa số thứ tự không thì chúng ta sét cột 0 vào
        //tblReport.mStrShowContent.Add("");//Tương ứng với 3 phần tử trên
        //tblReport.mArrPos[2] = 3;//1 ở đây là cột 1, cột 0 đã chứa số thứ tự không thì chúng ta sét cột 0 vào
        //tblReport.mStrShowContent.Add("");//Tương ứng với 3 phần tử trên
        tblReport.bShowGroupBy = false;
        //tblReport.mMaxLevel = 2;
        tblReport.BuidlASimpleByDB(tblReport, "zgcl_gcGobal_INCOM_Receipt_DetailAll", "zgcBUILDIN_CONFIG_REPORT_DETAIL", "351");
        tblReport.InitTable();
        tblReport.mArrArgSumary = new System.Collections.Generic.List<int>();
        for (int t = 0; t < tblReport.cCols; t++)
            tblReport.mArrArgSumary.Add(0);
        tblReport.mArrArgSumary[5] = 1;
        //tblReport.mArrArgSumary[7] = 1;
        //tblReport.mArrArgSumary[12] = 1;
        //-----------------------------------------------------------
        //BuilSampleTree(tblReport.root, tblReport);
        //-----------------------------------------------------------
        tblReport.MakeGobalRowForTesting();
        tblReport.FillData();//Kho Chủ

        //---------------------------------------------------
        //if (LoaiKhachId == "1") 
        //    for (int i = 0; i < tblReport.cCols; i++)
        //    {
        //        for (int j = 0; j < tblReport.mData.Count; j++)
        //        {
        //            if (i == 1 || i == 5 | i == 6)
        //                tblReport.mData[j][i] = "0";
        //            if (i == 1)
        //                tblReport.mData[j][i] = "";
        //        }
        //    }
        //--------------------------------------------------

       
        
        //------------------------------------------------------------
        double sum = 0;
        for (int i = 5; i < 6; i++)
        {
            for (int j = 0; j < tblReport.mData.Count; j++)
            {
                string value = (string)tblReport.mData[j][i];
                value.Trim();
                if (value != string.Empty)
                {
                    sum += double.Parse((string)value);
                }
            }
            tblReport.RowSumGobal.mValue[i] = sum.ToString();
            if (bEmpty)
            {
                sum = OldThucThu;
                tblReport.RowSumGobal.mValue[i] = OldThucThu.ToString();
            }
        }

        //Tong theo nhom và định dạng
        if (tblReport.mListItem.Count > 0)
        {
            for (int m = 0; m < tblReport.mListItem.Count; m++)
            {
                gcRptItem Item = tblReport.mListItem[m];
                Item.strShowName = "<b>Cộng </b>";
                Item.strContent = "Khách hàng " + tblReport.mData[Item.from][1];


                double Tem3 = 0;//, temp4 = 0;
                for (int j = 5; j < 6; j++)
                {
                    for (int i = Item.from; i < Item.to; i++)
                    {
                        string a5 = (string)tblReport.mData[i][j];
                        Tem3 += double.Parse((a5.Length < 1) ? "0" : a5);
                        Item.mValue[j] = Tem3.ToString();
                    }
                    Tem3 = 0;
                }
                Item.cssClass = "dhu_rpt_TextRight";
            }
        }

        //tblReport.RowSumGobal.cssClass = "dhu_rpt_TextRight";


        ////Xuất dữ liệu

        for (int t = 0; t < tblReport.cCols; t++)
        {
            tblReport.mArrRightStyle.Add(0);
            tblReport.mArrRightStyleCss.Add("");
        }
        //tblReport.RowSumGobal.cssClass = "dhu_rpt_TextRight";

        double valuept = 0;


        double valueg = 0;

        double VATg = 0;
        if (VAT > 0)
        {
            VATg = sum * VAT / 100;
            gcRptTailItem item = new gcRptTailItem();
            item.ColSpan = tblReport.cCols - 2;
            item.cssValueClass = "dhu_rpt_TextRight";
            item.strFormName = "Tiền thuế GTGT (VAT)" + VAT + "%";
            item.Value = String.Format("{0:N0}", VATg);
            tblReport.mListTailItem.Add(item);
        }
        valuept = 0;
        if (OldPhuThu > 0)
        {

            valuept = OldPhuThu;
            gcRptTailItem itemg = new gcRptTailItem();
            itemg.ColSpan = tblReport.cCols - 1;
            itemg.cssValueClass = "dhu_rpt_TextRight";
            itemg.strFormName = "Phụ thu (Tiền dịch vụ)";
            itemg.Value = String.Format("{0:N0}", (valuept));
            tblReport.mListTailItem.Add(itemg);
        }
        if (OldGiamGia > 0)
        {

            if (OldGiamGia > 0 && OldGiamGia < 100.0)
                valueg = OldGiamGia * sum / 100.0;
            else
                valueg = OldGiamGia;
            gcRptTailItem itemg = new gcRptTailItem();
            itemg.ColSpan = tblReport.cCols - 1;
            itemg.cssValueClass = "dhu_rpt_TextRight";
            itemg.strFormName = "Giảm giá (Discount)";
            if (OldGiamGia > 0 && OldGiamGia < 100.0)
                itemg.strFormName = "Giảm giá (Discount) " + OldGiamGia + "%";
            itemg.Value = String.Format("{0:N0}", (valueg));
            tblReport.mListTailItem.Add(itemg);
        }

        gcRptTailItem item2 = new gcRptTailItem();
        item2.cssValueClass = "dhu_rpt_TextRightBold";
        item2.ColSpan = tblReport.cCols - 1;
        item2.strFormName = "Tổng cộng tiền thanh toán";
        item2.Value = String.Format("{0:N0}", (sum + valuept - valueg + VATg));

	if (OldPhuThu > 0 || OldGiamGia > 0)
        	tblReport.mListTailItem.Add(item2);
	
	double tienphaithu =sum + valuept - valueg + VATg;


	//dhuConvertNumberToString NumberConvert = new dhuConvertNumberToString();
    string tientthu = dhuConvertNumberToString.Convert(tienphaithu);	
	//In tien ra cho khach
	gcRptTailItem TitemTien = new gcRptTailItem();
        TitemTien.cssValueClass = "dhu_rpt_TextRightBold";
        TitemTien.ColSpan = tblReport.cCols;
        TitemTien.strFormName = "<span style='font-style:italic; font-weight:bold;'>"+tientthu +"./</span>";
        TitemTien.Value = "";
      	tblReport.mListTailItem.Add(TitemTien );

        OldThucThu = (sum + valuept - valueg + VATg);
        //for (int i = 3; i < 4; i++)
        //{
        //    tblReport.mArrRightStyle[i] = 1;
        //    tblReport.mArrRightStyleCss[i] = "dhu_rpt_TextCenter";
        //}
        tblReport.mArrRightStyle[3] = 1; ;
        tblReport.mArrRightStyleCss[5] = "dhu_rpt_TextRight";

        tblReport.mArrRightStyle[3] = 1; ;
        tblReport.mArrRightStyleCss[2] = "dhu_rpt_TextLeft";

        tblReport.mArrRightStyle[1] = 1; ;
        tblReport.mArrRightStyleCss[1] = "dhu_rpt_TextLeft";
        
        //Xuất dữ liệu
        //
  

        tblReport.RowSumGobal.cssClass = "dhu_rpt_TextRightBold";
        tblReport.RowSumGobal.cssValueClass = "dhu_rpt_TextRightBold";
        
        table = tblReport.MakeSimpleTable();
        return table;
    }




}